package com.hd.trans.ui.fragment

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.transition.ChangeBounds
import android.transition.ChangeTransform
import android.transition.Fade
import android.transition.TransitionSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.DecelerateInterpolator
import android.view.animation.TranslateAnimation
import androidx.core.view.ViewCompat
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.binding.visible
import com.hd.trans.databinding.ActivitySimultaneousHome2Binding
import com.hd.trans.dialog.TongSettingDialog
import com.hd.trans.framework.click.SingleClick
import com.hd.trans.framework.click.XClickUtil
import com.hd.trans.homefun.EventCode
import com.hd.trans.network.PreferenceMgr
import com.hd.trans.ui.activity.SimulHomeActivity2
import com.hd.trans.ui.base.TransInit
import com.hd.trans.ui.model.SimultaneousModel
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.TrackerForTrans

@SuppressLint("SetTextI18n")
class SimulNormalFragment2(val theme: Int = 0) : SimulBaseFragment(), View.OnClickListener {
    private var floatAnim: ObjectAnimator? = null
    private lateinit var mDataBinding: ActivitySimultaneousHome2Binding
    private lateinit var mDataModel: SimultaneousModel
    private lateinit var mActivity: SimulHomeActivity2

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        mDataBinding = ActivitySimultaneousHome2Binding.inflate(inflater, container, false)
        mActivity = activity as SimulHomeActivity2
        initView()
        setThemeColor(theme)
        return mDataBinding.root
    }

    private fun setThemeColor(themeType: Int) {
        mDataBinding.apply {
            topLayout.backgroundTintList =
                ColorStateList.valueOf(TranslationInterior.getThemeColor())
            bottomLayout.backgroundTintList =
                ColorStateList.valueOf(TranslationInterior.getThemeColor())

            when(themeType){
                0 -> {
                    //原有样式
                    ivTopTheme.setBackgroundColor(TranslationInterior.getThemeColor())
                    layoutTitle.ivRight.imageTintList = ColorStateList.valueOf(resources.getColor(R.color.white))
                }
                else -> {
                    ivTopTheme.setBackgroundColor(Color.WHITE)
                    llContentLayout.setBackgroundColor(Color.WHITE)
                    rlTopLayout.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.color_F3F6F9))
                    rlBottomLayout.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.color_F3F6F9))
                    layoutTitle.ivLeft.imageTintList = ColorStateList.valueOf(resources.getColor(R.color.black_222))
                    layoutTitle.ivRight.imageTintList = ColorStateList.valueOf(resources.getColor(R.color.transparent))
                    layoutTitle.iconExchange.imageTintList = ColorStateList.valueOf(TranslationInterior.getThemeColor())
                    layoutTitle.ivDirectionDown1.imageTintList = ColorStateList.valueOf(resources.getColor(R.color.black_222))
                    layoutTitle.ivDirectionDown2.imageTintList = ColorStateList.valueOf(resources.getColor(R.color.black_222))
                    layoutTitle.tvFrom.setTextColor(resources.getColor(R.color.black_222))
                    layoutTitle.tvTo.setTextColor(resources.getColor(R.color.black_222))
                }
            }
        }
    }

    private fun initView() {
        mDataBinding.apply {
            layoutTitle.ivRight.setImageResource(R.mipmap.trans_tong_set)
            layoutTitle.ivLeft.setOnClickListener(this@SimulNormalFragment2)
            layoutTitle.ivRight.setOnClickListener(this@SimulNormalFragment2)
            topLayout.setOnClickListener(this@SimulNormalFragment2)
            bottomLayout.setOnClickListener(this@SimulNormalFragment2)
            layoutTitle.leftBt.setOnClickListener(this@SimulNormalFragment2)
            layoutTitle.iconExchange.setOnClickListener(this@SimulNormalFragment2)
            layoutTitle.rightBt.setOnClickListener(this@SimulNormalFragment2)

            if (SimulHomeActivity2.mOpenSceneTransition) { //共享元素动画
                mActivity.window.enterTransition = Fade()
                mActivity.window.exitTransition = Fade()
                ViewCompat.setTransitionName(ivMkf1,
                    resources.getString(R.string.share_simultaneous_one))
                ViewCompat.setTransitionName(ivMkf2,
                    resources.getString(R.string.share_simultaneous_two))
                /**
                 * 3、设置ShareElementTransition,指定的ShareElement会执行这个Transiton动画
                 * 可设定ChangeBounds、ChangeTransform对象的属性值改变动画效果
                 */
                val transitionSet = TransitionSet()
                transitionSet.addTransition(ChangeBounds())
                transitionSet.addTransition(ChangeTransform())
                transitionSet.addTarget(ivMkf1)
                transitionSet.addTarget(ivMkf2)
                mActivity.window.sharedElementEnterTransition = transitionSet
                mActivity.window.sharedElementExitTransition = transitionSet
            }
            ivMkf1.postDelayed({ ivMkf1.setBackgroundColor(Color.TRANSPARENT) }, 500)
            ivMkf2.postDelayed({ ivMkf2.setBackgroundColor(Color.TRANSPARENT) }, 500)

            llTipsNew.visible = !PreferenceMgr.getInstance().isTongNewTip
            if(llTipsNew.visible){
                //浮动
                floatAnim = ObjectAnimator.ofFloat(llTipsNew, View.TRANSLATION_Y.name, 0f, 20f,0f)
                floatAnim?.duration = 2000 //持续时间
                floatAnim?.repeatCount = Animation.INFINITE//循环
                floatAnim?.startDelay = 1000
                floatAnim?.interpolator = DecelerateInterpolator()//插值器
                llTipsNew.postDelayed({
                    hideFloatTips()
                },6000)
            }
        }
    }

    private fun startFloatAnim(){
        if(floatAnim?.isRunning == false){
            floatAnim?.start()
        }
    }

    private fun stopFloatAnim(){
        floatAnim?.cancel()
        mDataBinding.llTipsNew.translationY = 0f
    }

    private fun hideFloatTips(){
        floatAnim?.cancel()
        floatAnim = null
        mDataBinding.llTipsNew.animate().alpha(0f).setDuration(500).start()
    }

    /**
     * 互换语种动画
     */
    private fun showTranslateAnimation() {
        if ("自动检测" == mDataModel.languageFrom.value!!.name) {
            ToastUtils.showNormal(resources.getString(R.string.tips_to_not_auto))
            return
        }
        val ta1 = TranslateAnimation(
            0f, 
            (mDataBinding.layoutTitle.leftBt.width + mDataBinding.layoutTitle.iconExchange.width).toFloat(),
            0f, 
            0f)
        ta1.duration = 600
        ta1.fillAfter = true
        mDataBinding.layoutTitle.leftBt.startAnimation(ta1)
        mDataBinding.layoutTitle.leftBt.bringToFront()
        val ta2 = TranslateAnimation(
            0f, 
            (-mDataBinding.layoutTitle.rightBt.width - mDataBinding.layoutTitle.iconExchange.width).toFloat(), 
            0f, 
            0f)
        ta2.duration = 600
        ta2.fillAfter = true
        mDataBinding.layoutTitle.rightBt.startAnimation(ta2)
        mDataBinding.layoutTitle.rightBt.bringToFront()
        ta1.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                val fromTemp = mDataModel.languageFrom.value
                mDataModel.setLanguageFrom(mDataModel.languageTo.value)
                mDataModel.setLanguageTo(fromTemp)
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        ta2.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
    }

    public override fun onlazyLoad() {
        mDataModel = mActivity.mDataModel
        mDataModel.languageFrom.observe(this) { huDunLanguage ->
            if (huDunLanguage != null) {
                mDataBinding.layoutTitle.tvFrom.text = huDunLanguage.name
                mDataBinding.topButton.text = huDunLanguage.shortName
                if (TransInit.getLanguageTipsMap() != null && TransInit.getLanguageTipsMap()[huDunLanguage.name] != null && TransInit.getLanguageTipsMap()[huDunLanguage.name]!!
                        .tips != null
                ) {
                    mDataBinding.topTip.text = TransInit.getLanguageTipsMap()[huDunLanguage.name]!!
                        .tips
                } else {
                    mDataBinding.topTip.text = "点击按钮开始说" + huDunLanguage.name
                }
            }
        }
        mDataModel.languageTo.observe(this) { huDunLanguage ->
            if (huDunLanguage != null) {
                mDataBinding.layoutTitle.tvTo.text = huDunLanguage.name
                mDataBinding.bottomButton.text = huDunLanguage.shortName
                if (TransInit.getLanguageTipsMap() != null
                    && TransInit.getLanguageTipsMap()[huDunLanguage.name] != null
                    && TransInit.getLanguageTipsMap()[huDunLanguage.name]!!.tips != null
                ) {
                    mDataBinding.bottomTip.text = TransInit.getLanguageTipsMap()[huDunLanguage.name]!!
                        .tips
                } else {
                    mDataBinding.bottomTip.text = "点击按钮开始说" + huDunLanguage.name
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        startFloatAnim()
    }

    override fun onPause() {
        super.onPause()
        stopFloatAnim()
    }

    override fun onBackPressed(): Boolean {
        mDataBinding.ivMkf1.setBackgroundResource(R.drawable.shape_oval_blue)
        mDataBinding.ivMkf2.setBackgroundResource(R.drawable.shape_oval_blue)
        if(SimulHomeActivity2.mOpenSceneTransition){
            return false;
        }
        mActivity.finish()
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        mDataModel.languageFrom.removeObservers(this)
        mDataModel.languageTo.removeObservers(this)
    }

    public override fun onDataFresh() {}

    @SingleClick
    override fun onClick(v: View) {
        if (XClickUtil.isFastDoubleClick(v, XClickUtil.INTERVAL_MILLIS.toLong())) {
            return
        }
        mDataBinding.apply {
            when(v){
                topLayout -> {
                    if (mActivity.isLimit4Use(EventCode.SIMUL_TRANSLATE)) mActivity.changeFragment(
                        SimulHomeActivity2.TOP)
                }
                bottomLayout -> {
                    if (mActivity.isLimit4Use(EventCode.SIMUL_TRANSLATE)) {
                        val fromTemp = mDataModel.languageFrom.value
                        mDataModel.setLanguageFrom(mDataModel.languageTo.value)
                        mDataModel.setLanguageTo(fromTemp)
                        mActivity.changeFragment(SimulHomeActivity2.TOP)
                    }
                }
                layoutTitle.ivLeft -> {
                    ivMkf1.setBackgroundResource(R.drawable.shape_oval_blue)
                    ivMkf2.setBackgroundResource(R.drawable.shape_oval_blue)
                    mActivity.onBackPressed()
                }
                layoutTitle.ivRight -> {
                    //埋点
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.TSCY,TrackerForTrans.SETTING)
                    PreferenceMgr.getInstance().isTongNewTip = true
                    hideFloatTips()

                    TongSettingDialog().apply {
                        confirm = { isChecked ->
                            PreferenceMgr.getInstance().isAllowSaveChecked = isChecked
                            val msg = if(isChecked){
                                //埋点
                                TranslationInterior.getTrackerListener().click(TrackerForTrans.TSCY, TrackerForTrans.SELECT_RECORDING)
                                "已开启"
                            }else{
                                "已关闭"
                            }
                            ToastUtils.showNormal(msg)
                        }
                    }.show(mActivity.supportFragmentManager,"tong")
                }
                layoutTitle.leftBt -> {
                    mActivity.showLanguageDialog(true)
                }
                layoutTitle.rightBt -> {
                    mActivity.showLanguageDialog(false)
                }
                layoutTitle.iconExchange -> {
                    showTranslateAnimation()
                }
            }
        }
    }
}